﻿using JNPF.Logging;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using PARK.Dependency;
using PARK.DynamicApiController;
using PARK.TaskScheduler.Interfaces;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace PARK.TaskScheduler
{
    /// <summary>
    /// 考勤记录任务
    /// </summary>
    [ApiDescriptionSettings(Tag = "AttendRecordJob", Name = "attendRecordJobtask", Order = 220)]
    [Route("api/[controller]")]
    public class AttendRecordJobService : BackgroundService, IAttendRecordJobService, IDynamicApiController, ITransient
    {
        private readonly SqlSugarScope _db;

        public AttendRecordJobService(
            ISqlSugarClient db)
        {
            _db = (SqlSugarScope)db;
        }
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {

        }

        /// <summary>
        /// 启动自启动任务
        /// </summary>
        [NonAction]
        public async void StartTimerJob()
        {
            new LoggEx().Info("考勤记录->队列开始执行...");
            CancellationToken stoppingToken = new CancellationToken();
            while (!stoppingToken.IsCancellationRequested)
            {
                await new TaskFactory().StartNew(() =>
                {
                    try
                    {
                        if (DateTime.Now.Hour == 1 && DateTime.Now.Millisecond == 30)
                        {
                            RunAttendrecordQueue();
                        }
                    }
                    catch (Exception e)
                    {
                        new LoggEx().Info("考勤记录,队列异常:=============失败=====" + e.Message);
                    }
                    //定时任务休眠
                    Thread.Sleep(500);
                });
            }
        }

        #region 处理考勤记录
        /// <summary>
        /// 处理考勤记录
        /// </summary>
        void RunAttendrecordQueue()
        {
            try
            {
                var Paras = new List<SugarParameter>();
                var companys = _db.Ado.GetDataTable("select F_Id from base_organize where F_ParentId='-1' and uni_is=1");
                for (int i = 0; i < companys.Rows.Count; i++)
                {
                    var Pars = new List<SugarParameter>(){
                                        new SugarParameter("@querytime",DateTime.Now.AddDays(-1).Date.ToString("yyyy-MM-dd")),
                                        new SugarParameter("@CompanyId",companys.Rows[i]["F_Id"].ToString())
                                    };
                    _db.Ado.UseStoredProcedure().ExecuteCommand("P_Attend_records_Add", Pars);
                }
            }
            catch (Exception ex)
            {
                new LoggEx().errlog("处理考勤记录,异常:" + ex.Message);
            }
        }
        #endregion
    }
}
